<template>
  <div class="city-multi-select">
    <!-- 省份选择 -->
    <a-select
      v-model:value="selectedProvince"
      :options="provinceOptions"
      :placeholder="provincePlaceholder"
      :loading="loading"
      style="width: 200px; margin-right: 2%"
      @focus="loadProvinces"
      @change="handleProvinceChange"
    />
    
    <!-- 城市选择 -->
    <a-select
      v-model:value="selectedCity"
      :options="cityOptions"
      :placeholder="cityPlaceholder"
      :disabled="!selectedProvince"
      :loading="loading"
      style="width: 200px; margin-right: 2%"
      @focus="loadCities"
      @change="handleCityChange"
    />
    
    <!-- 区县选择 -->
    <a-select
      v-model:value="selectedDistrict"
      :options="districtOptions"
      :placeholder="districtPlaceholder"
      :disabled="!selectedCity"
      :loading="loading"
      style="width: 200px; margin-right: 2%"
      @focus="loadDistricts"
      @change="handleDistrictChange"
    />
    
    <!-- 街道选择 -->
    <a-select
      v-model:value="selectedStreet"
      :options="streetOptions"
      :placeholder="streetPlaceholder"
      :disabled="!selectedDistrict"
      :loading="loading"
      style="width: 200px"
      @focus="loadStreets"
      @change="handleStreetChange"
    />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import {$apiSubListQueryOrgTree,$apiSubListQueryAgentList} from '@/api/proxy/accountMange/index'

const props = defineProps({
  provincePlaceholder: {
    type: String,
    default: '请选择省份'
  },
  cityPlaceholder: {
    type: String,
    default: '请选择城市'
  },
  districtPlaceholder: {
    type: String,
    default: '请选择区县'
  },
  streetPlaceholder: {
    type: String,
    default: '请选择街道'
  },
  defaultValue: {
    type: Object,
    default: () => ({})
  },
  apiUrl: {
    type: String,
    default: '/api/regions'
  }
})

const emit = defineEmits(['change'])

// 选中的值
const selectedProvince = ref(props.defaultValue.province || '')
const selectedCity = ref(props.defaultValue.city || '')
const selectedDistrict = ref(props.defaultValue.district || '')
const selectedStreet = ref(props.defaultValue.street || '')

// 选项数据
const provinceOptions = ref([])
const cityOptions = ref([])
const districtOptions = ref([])
const streetOptions = ref([])

// 加载状态
const loading = ref(false)

// 缓存已加载的数据
const cache = ref({
  provinces: [],
  cities: {},
  districts: {},
  streets: {}
})

// 获取区域数据
// const fetchRegionData = async (parentId = '41022445') => {
//   loading.value = true
//   try {
//     const response = await $apiSubListQueryOrgTree({agentNo: parentId})
//     console.log('接口返回数据:', response)
    
//     // 处理返回的数据结构
//     if (!response || !response.children) {
//       return []
//     }
    
//     // 如果返回的是单个对象（如省级数据），将其转换为数组格式
//     const data = Array.isArray(response) ? response : [response]
    
//     // 格式化数据
//     const formattedData = data.map(item => {
//       // 处理children数据（如果存在）
//       const children = item.children ? item.children.map(child => ({
//         value: child.agentNo,
//         label: child.agentName || child.addr,
//         children: child.children || [],
//         rawData: child
//       })) : []
      
//       return {
//         value: item.agentNo,
//         label: item.agentName || item.addr,
//         children: children,
//         rawData: item
//       }
//     })
    
//     console.log('格式化后的数据:', formattedData)
//     return formattedData
//   } catch (error) {
//     console.error('请求错误:', error)
//     message.error('数据加载失败')
//     return []
//   } finally {
//     loading.value = false
//   }
// }

const fetchRegionData = async (parentId = '') => {
  loading.value = true
  try {
    const response = await $apiSubListQueryAgentList({agentNo: parentId})
    console.log(response,'机构数据1111')

    const data = response
    return data?.map(item => ({
      value: item.agentNo,
      label: item.agentName || item.addr,
      children: item.children || [],
      rawData: item
    }))
  } catch (error) {
    console.error('请求错误:', error)
    message.error('数据加载失败')
    return []
  } finally {
    loading.value = false
  }
}

// 加载省份数据
const loadProvinces = async () => {
  if (provinceOptions.value.length > 0) return
  
  if (cache.value.provinces.length > 0) {
    provinceOptions.value = cache.value.provinces
    return
  }
  
  const data = await fetchRegionData('')
  provinceOptions.value = data
  cache.value.provinces = data
}

// 加载城市数据
const loadCities = async () => {
  if (!selectedProvince.value) return
  
  if (cache.value.cities[selectedProvince.value]) {
    cityOptions.value = cache.value.cities[selectedProvince.value]
    return
  }
  
  const province = cache.value.provinces.find(p => p.value === selectedProvince.value)
  if (province && province.children && province.children.length > 0) {
    console.log(cityOptions.value,'城市数据')
    cityOptions.value = province.children.map(item => ({
      value: item.agentNo,
      label: item.agentName || item.addr,
      children: item.children || [],
      rawData: item
    }))
    cache.value.cities[selectedProvince.value] = cityOptions.value
  } else {
    console.log(selectedProvince.value,88887777)
    const data = await fetchRegionData(selectedProvince.value)
    cityOptions.value = data
    cache.value.cities[selectedProvince.value] = data
  }
}

// 加载区县数据
const loadDistricts = async () => {
  if (!selectedCity.value) return
  
  if (cache.value.districts[selectedCity.value]) {
    districtOptions.value = cache.value.districts[selectedCity.value]
    return
  }
  
  const city = cache.value.cities[selectedProvince.value]?.find(c => c.value === selectedCity.value)
  if (city && city.children && city.children.length > 0) {
    districtOptions.value = city.children.map(item => ({
      value: item.agentNo,
      label: item.agentName || item.addr,
      children: item.children || [],
      rawData: item
    }))
    cache.value.districts[selectedCity.value] = districtOptions.value
  } else {
    const data = await fetchRegionData(selectedCity.value)
    districtOptions.value = data
    cache.value.districts[selectedCity.value] = data
  }
}

// 加载街道数据
const loadStreets = async () => {
  if (!selectedDistrict.value) return
  
  if (cache.value.streets[selectedDistrict.value]) {
    streetOptions.value = cache.value.streets[selectedDistrict.value]
    return
  }
  
  const district = cache.value.districts[selectedCity.value]?.find(d => d.value === selectedDistrict.value)
  if (district && district.children && district.children.length > 0) {
    streetOptions.value = district.children.map(item => ({
      value: item.agentNo,
      label: item.agentName || item.addr,
      rawData: item
    }))
    cache.value.streets[selectedDistrict.value] = streetOptions.value
  } else {
    const data = await fetchRegionData(selectedDistrict.value)
    streetOptions.value = data
    cache.value.streets[selectedDistrict.value] = data
  }
}

// 省份变化处理
const handleProvinceChange = (value) => {
  selectedCity.value = ''
  selectedDistrict.value = ''
  selectedStreet.value = ''
  cityOptions.value = []
  districtOptions.value = []
  streetOptions.value = []
  emitChange()
}

// 城市变化处理
const handleCityChange = (value) => {
  selectedDistrict.value = ''
  selectedStreet.value = ''
  districtOptions.value = []
  streetOptions.value = []
  emitChange()
}

// 区县变化处理
const handleDistrictChange = (value) => {
  selectedStreet.value = ''
  streetOptions.value = []
  emitChange()
}

// 街道变化处理
const handleStreetChange = () => {
  emitChange()
}

// 触发change事件
const emitChange = () => {
  emit('change', {
    province: selectedProvince.value,
    city: selectedCity.value,
    district: selectedDistrict.value,
    street: selectedStreet.value,
    fullPath: [
      selectedProvince.value,
      selectedCity.value,
      selectedDistrict.value,
      selectedStreet.value
    ].filter(Boolean),
    rawData: {
      province: cache.value.provinces.find(p => p.value === selectedProvince.value)?.rawData,
      city: cache.value.cities[selectedProvince.value]?.find(c => c.value === selectedCity.value)?.rawData,
      district: cache.value.districts[selectedCity.value]?.find(d => d.value === selectedDistrict.value)?.rawData,
      street: cache.value.streets[selectedDistrict.value]?.find(s => s.value === selectedStreet.value)?.rawData
    }
  })
}

// 初始化默认值
const initDefaultValues = async () => {
  if (props.defaultValue.province) {
    await loadProvinces()
    selectedProvince.value = props.defaultValue.province
    
    if (props.defaultValue.city) {
      await loadCities()
      selectedCity.value = props.defaultValue.city
      
      if (props.defaultValue.district) {
        await loadDistricts()
        selectedDistrict.value = props.defaultValue.district
        
        if (props.defaultValue.street) {
          await loadStreets()
          selectedStreet.value = props.defaultValue.street
        }
      }
    }
  }
}

// 监听默认值变化
watch(() => props.defaultValue, (newVal) => {
  if (newVal.province !== selectedProvince.value || 
      newVal.city !== selectedCity.value || 
      newVal.district !== selectedDistrict.value || 
      newVal.street !== selectedStreet.value) {
    initDefaultValues()
  }
}, { immediate: true })
</script>

<style scoped>
.city-multi-select {
  display: flex;
  justify-content: space-between;
}
</style>